const express = require("express")
const router = express.Router()
const bcrypt = require("bcryptjs")

const UserModel = require("./UserModel")
const auth = require("./checkToken")
const createToken = require("./createToken")

router.get("/", (req, res) => {
  res.send("hello jwt")
})

router.post("/register", (req, res) => {
  const { username, password } = req.body
  UserModel.findOne({ username })
    .then((user) => {
      if (user) {
        res.send({ status: 1, msg: "此用户已注册" })
        return new Promise(() => {})
      } else {
        return UserModel.create({ username, password })
      }
    })
    .then((user) => {
      res.send({
        status: 0,
        data: {
          _id: user._id,
          username: user.username,
          token_key: createToken(user._id),
        },
      })
    })
    .catch((error) => {
      console.error("注册异常", error)
      res.send({ status: 1, msg: "添加用户异常,请重新尝试" })
    })
})

router.post("/login", (req, res) => {
  const { username, password } = req.body
  UserModel.findOne({ username })
    .then((user) => {
      const isPasswordValid = bcrypt.compareSync(password, user.password)
      if (!isPasswordValid) {
        res.send({ status: 1, msg: "用户名或密码错误" })
      }
      res.send({
        status: 0,
        data: {
          _id: user._id,
          username: user.username,
          token_key: createToken(user._id),
        },
      })
    })
    .catch((error) => {
      console.error("登录异常", error)
      res.send({ status: 1, msg: "登录异常,请重新尝试" })
    })
})

router.post("/profile", auth, (req, res) => {
  res.send({ data: req.user })
})

module.exports = router
